#include "tool.h"

#include <iostream>

#include <QDateTime>
#include <QFile>
#include <QHeaderView>

const QString Tool::DATETIME_FORMAT = "yyyy.MM.dd HH:mm:ss";

void Tool::setTableHeaders(QTableWidget* table, const QStringList& horizontalLabels)
{
    table->setColumnCount(horizontalLabels.size());
    table->setHorizontalHeaderLabels(horizontalLabels);
    table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

void Tool::appendTableRow(QTableWidget* table, const QStringList& items)
{
    int row = table->rowCount();
    table->insertRow(row);

    for (int c = 0; c < items.size(); ++c)
    {
        auto item = new QTableWidgetItem(items[c]);
        item->setTextAlignment(Qt::AlignCenter);
        table->setItem(row, c, item);
    }
}

void Tool::messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message)
{
    QString text = QDateTime::currentDateTime().toString(DATETIME_FORMAT) + ": ";

    switch (type)
    {
        case QtDebugMsg:
            text += QString("[Debug] (file %1, func %2, line %3)").arg(context.file).arg(context.function).arg(context.line);
            break;

        case QtWarningMsg:
            text += QString("[Warning] (file %1, func %2, line %3)").arg(context.file).arg(context.function).arg(context.line);
            break;

        case QtCriticalMsg:
            text += QString("[Critical] (file %1, func %2, line %3)").arg(context.file).arg(context.function).arg(context.line);
            break;

        case QtFatalMsg:
            text += QString("[Fatal] (file %1, func %2, line %3)").arg(context.file).arg(context.function).arg(context.line);
            break;

        case QtInfoMsg:
            text += "[Info]";
            break;

        default:
            break;
    }

    text += " " + message + "\n";

    std::cerr << text.toStdString();

    QFile log("log.txt");
    log.open(QIODevice::Append);
    log.write(text.toLocal8Bit());
    log.close();
}
